<?php
/**
 * Created by PhpStorm.
 * User: lyq
 * Date: 2018/11/17
 * Time: 上午10:00
 */

namespace app\common\model;

use think\Db;


class Goods extends Common
{
    protected function base($query)
    {
        $query->where("status", 1);
    }

    /**
     * 格式化商品价格
     */
    protected static function goodsFormatPrice($list)
    {
        $user = User::exists(session("user_id"));
        foreach ($list as &$hitem) {
            $hitem["price"] = self::goodFormatOne($user, $hitem["brand_id"], $hitem["price"]);
        }
        return $list;
    }

    /**
     * 格式化单个商品价格
     */
    protected static function goodFormatOne($user, $brand_id, $price)
    {
        return in_array($brand_id, explode(",", $user["brand_id"])) ? $price : "品牌会员价格可见";
    }

    /**
     * 根据给定条件查询商品列表
     */
    public static function getGoodsByCondition($keywords = "", $cate_id = 0, $brand_id = 0, $sort_key = "id", $sort_type = "desc", $is_page = true, $page = "", $page_num = 20, $presell_id=0)
    {
        $model = new self();
        $model->alias("a")->join("brand b", "a.brand_id=b.id")->where("a.is_index", 1)->field("a.id, a.title, a.brand_id, a.price, b.title brand_title, a.img_url, a.use_spec");
        if (!empty($keywords)) {
            $model->whereLike("a.title|a.short_title|a.keyword", "%" . $keywords . "%");
        }
        if (!empty($cate_id)) {
            $model->where("a.category_id1|a.category_id2|a.category_id3", $cate_id);
        }
        if (!empty($brand_id)) {
            $model->where("a.brand_id", $brand_id);
        }
        if (!empty($sort_key)) {
            $model->order("a.$sort_key $sort_type, a.display_order desc");
        } else {
            $model->order("a.display_order desc, id desc");
        }
        $model->where("a.presell_id", $presell_id);
        if ($is_page) {
            $model->limit(($page - 1) * $page_num, $page_num);
        }
        return self::goodsFormatPrice($model->select());
    }

    /**
     * 获取热卖商品
     */
    public static function getHotList($is_index = 1, $page = 1, $page_num = 20, $sort_key = "", $sort_type = "")
    {
        $model = new self();
        $model->alias("a")->join("brand b", "a.brand_id=b.id")->where("a.presell_id", 0)->where("a.is_index", 1)->field("a.id, a.title, a.brand_id, a.price, b.title brand_title, a.img_url, a.use_spec");
        if (!empty($sort_key)) {
            $model->order("a.$sort_key $sort_type, a.display_order desc");
        } else {
            $model->order("a.display_order desc, id desc");
        }
        if ($is_index) {
            $model->limit(0, 4);
        } else {
            $model->limit(($page - 1) * $page_num, $page_num);
        }
        return self::goodsFormatPrice($model->select());
    }

    /**
     * 根据产品id获取产品状态
     */
    static public function check($goods_id)
    {
        $info = Db::name('goods')
            ->where('id', $goods_id)
            ->find();

        if (!$info) {
            throw new UserException('不好意思，商品找不到了！');
        }
        if ($info['status'] != 1) {
            throw new UserException('该商品已下架！');
        }
        $price = self::goodFormatOne(User::exists(session("user_id")), $info["brand_id"], $info["price"]);
        if(!is_numeric($price)){
            $info["price"] = $price;
            $info["original_price"] = $price;
        }
        return $info;
    }

    /**
     *  获取商品规格信息
     */
    public static function getSpec($good_id)
    {
        $good = self::check($good_id);
        $options = \db("goods_spec")->where("goods_id", $good_id)->field("id spec_id, goods_id good_id,  title spec_title, price spec_price, img_url")->select();
        $user = User::exists(session('user_id'));
        foreach ($options as &$opt) {
            $opt['spec_price'] = self::goodFormatOne($user, $good["brand_id"], $opt["spec_price"]);
        }
        return [
            "good" => [
                "good_id" => $good["id"],
                "good_img_url" => $good["img_url"],
                "good_price" => self::goodFormatOne($user, $good["brand_id"], $good["price"]),
                "good_title" => $good["title"]
            ],
            "options" => $options
        ];
    }

    /**
     * 获取商品轮播图
     */
    public static function getSwiper($good_id)
    {
        $swiper_list = \db("goods_img")->where("goods_id", $good_id)->column("img_url");
        return empty($swiper_list) ? [] : $swiper_list;
    }

    /**
     * 获取相关推荐
     */
    public static function getRelative($good_id)
    {
        $list = \db("good_relative")->alias("a")->join("goods b", "a.relative_id=b.id")->where("a.good_id", $good_id)->order("b.display_order desc")->field("b.id id, b.title, b.img_url, b.price, b.brand_id")->select();
        return self::goodsFormatPrice($list);
    }

    /**
     * 获取热门搭配
     */
    public static function getRecommend($good_id)
    {
        $list = \db("good_recommend")->alias("a")->join("goods b", "a.relative_id=b.id")->where("a.good_id", $good_id)->order("b.display_order desc")->field("b.id id, b.title, b.img_url, b.price, b.brand_id")->select();
        return self::goodsFormatPrice($list);
    }

    /**
     * 获取商品评论
     */
    public static function getComment($good_id, $page=1, $page_num=20)
    {
        return \db("goods_comment")->alias("a")->join("user b", "a.uid=b.id")->where("a.goods_id", $good_id)->field("a.star, a.content, a.comment_time, b.avatar, b.nick_name")->order("comment_time desc")->limit(($page-1)*$page_num, $page_num)->select();
    }

    /**
     * 检验是否为收藏
     */
    public static function checkCollect($goods_id)
    {
        $s = \db("goods_collection")->where("goods_id", $goods_id)->where("uid", session("user_id"))->find();
        return empty($s)?0:1;
    }


    /**
     * 我的收藏
     */
    static public function myCollect($user_id, $page = 1, $page_size = 10)
    {
        $list = Db::name('goods_collection')
            ->alias('gc')
            ->join('__GOODS__ g', 'g.id=gc.goods_id')
            ->join("brand brand", "g.brand_id=brand.id")
            ->where('gc.uid', $user_id)
            ->field('gc.id as id,g.id as goods_id,g.img_url,g.title,g.price,brand.title brand_title')
            ->order('gc.id DESC')
            ->page($page, $page_size)
            ->select();
        return empty($list) ? [] : $list;
    }

    /**
     * 根据收藏id收藏删除
     * @param $user_id
     * @param $del_id
     * @return string
     * @throws UserException
     */
    static public function myCollectRemove($user_id, $del_id)
    {
        $del_id = explode(',', $del_id);
        foreach ($del_id as $key => $item) {
            if (empty($item)) {
                unset($del_id[$key]);
            }
        }
        if (count($del_id) <= 0) {
            throw new UserException('请选择要删除的收藏！');
        }

        Db::name('goods_collection')
            ->where('uid', $user_id)
            ->where('id', 'in', $del_id)
            ->delete();
        return '删除成功';
    }

}
